package com.ruoyi.framework.config;

import com.ruoyi.framework.intercepter.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

@Configuration
public class WebMvcConfigurer implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer {

    @Bean
    public HandlerInterceptor getTokenInterceptor() {
        // 提前加载为了使用注解
        return new JwtInterceptor();
    }

    //增加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getTokenInterceptor())    //指定拦截器类
                .addPathPatterns("/app/**")
                .excludePathPatterns("/app/login")
                .excludePathPatterns("/app/login/sendCode")
                .excludePathPatterns("/app/login/verify")
                .excludePathPatterns("/app/commodity/**")
                .excludePathPatterns("/app/my/selectUserProtocolList")
                .excludePathPatterns("/app/product/**")
                .excludePathPatterns("/app/advertisement/**")
                .excludePathPatterns("/app/notice/**");//指定该类不拦截的url
    }

//    @Bean
//    public FilterRegistrationBean jwtFilter() {
//        final FilterRegistrationBean<JwtFilter> registrationBean = new FilterRegistrationBean<>();
//        JwtFilter jwtFilter = new JwtFilter();
//        registrationBean.setFilter(jwtFilter);
//        registrationBean.addUrlPatterns("/app/**");
//        return registrationBean;
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置请求跨域
        registry.addMapping("/app/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(3600);
    }

//    @Bean
//    public CorsFilter corsFilter() {
//        // 设置请求跨域
//        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.addAllowedOrigin("*"); // 1
//        corsConfiguration.addAllowedHeader("*"); // 2
//        corsConfiguration.addAllowedMethod("*"); // 3
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/app/**", corsConfiguration);
//        return new CorsFilter(source);
//    }

}